# split cut 函数，用于推理语句切分
# 定义标点符号，用于文本切分处理
punctuation = {'!', '?', '…', ',', '.', '-', " "}
splits = {"，", "。", "？", "！", ",", ".", "?", "!", "~", ":", "：", "—", "…", }

def split(todo_text):
    todo_text = todo_text.replace("……", "。").replace("——", "，")
    if todo_text[-1] not in splits:
        todo_text += "。"
    i_split_head = i_split_tail = 0
    len_text = len(todo_text)
    todo_texts = []
    while 1:
        if i_split_head >= len_text:
            break  # 结尾一定有标点，所以直接跳出即可，最后一段在上次已加入
        if todo_text[i_split_head] in splits:
            i_split_head += 1
            todo_texts.append(todo_text[i_split_tail:i_split_head])
            i_split_tail = i_split_head
        else:
            i_split_head += 1
    return todo_texts


def cut_with_four_sentences(inp):
    inp = inp.strip("\n")
    inps = split(inp)
    split_idx = list(range(0, len(inps), 4))
    split_idx[-1] = None
    if len(split_idx) > 1:
        opts = []
        for idx in range(len(split_idx) - 1):
            opts.append("".join(inps[split_idx[idx]: split_idx[idx + 1]]))
    else:
        opts = [inp]
    opts = [item for item in opts if not set(item).issubset(punctuation)]
    return "\n".join(opts)


def cut_with_punctuation(inp):
    inp = inp.strip("\n")
    mergeitems = []
    items = []

    for i, char in enumerate(inp):
        if char in splits:
            if char == '.' and i > 0 and i < len(inp) - 1 and inp[i - 1].isdigit() and inp[i + 1].isdigit():
                items.append(char)
            else:
                items.append(char)
                mergeitems.append("".join(items))
                items = []
        else:
            items.append(char)

    if items:
        mergeitems.append("".join(items))

    opt = [item for item in mergeitems if not set(item).issubset(splits)]
    return opt


def merge_short_sentence(sentence_list, threshold):
    if len(sentence_list) < 2:
        return sentence_list

    result = []
    merge = ""
    for sentence in sentence_list[:-1]:  # 不处理最后一个，最后一个可能是未完全出现的句子
        merge += sentence
        if len(merge) >= threshold:
            result.append(merge)
            merge = ""

    if len(merge) > 0:  # 末尾长度不足的分句
        if len(result) == 0:
            result.append(merge)
        else:  # 非空向前合并
            result[-1] += merge

    # 根据最后一句是否为完整分句进行合并操作
    if is_complete_sentence(sentence_list[-1]):  # 是完整分句
        if len(sentence_list[-1]) < threshold:  # 长度小于阈值，需要合并
            result[-1] += sentence_list[-1]
        else:  # 不需要合并
            result.append(sentence_list[-1])
    else:  # 不是完整分句
        result.append(sentence_list[-1])  # 直接把最后一个添加到末尾

    return result


def is_complete_sentence(sentence):
    """
    判断一个句子是否是完整的分句（即是否以标点符号结尾）
    输入:
        sentence (str): 输入的句子
    输出:
        bool: 如果句子是完整的分句，返回 True；否则返回 False
    """

    # 去掉句子的首尾空格
    sentence = sentence.strip()

    # 判断句子是否以标点符号结尾
    if sentence and sentence[-1] in splits:
        return True
    else:
        return False

